<!-- 个人中心 -->
<template>
    <div>
        <div class="user-container">
            <el-card class="user-profile" shadow="hover" :body-style="{ padding: '0px' }">
                <div class="user-profile-bg" :style="{ backgroundImage: 'url(' + imgDecoration + ')' }"></div>
                <div class="user-avatar-wrap">
                    <el-avatar class="user-avatar" :size="120" :src="avatarImg" />
                </div>
                <div class="user-info" >
                    <div class="info-name">{{ name }}</div>
                    <div class="info-desc" v-if="role !='club'" >
                        <span>{{sex}}</span>
                        <el-divider direction="vertical" />
                        <el-link target="_blank">{{age}}</el-link>
                    </div>
                
                    <div class="info-icon" v-if="role !='club'" >
                        <span>个性签名：</span>
                        <span>{{description}}</span>
                    </div>
                </div>
                <div class="user-footer">
                    <div class="user-footer-item">
                        <el-statistic title="成员" :value="1800" />
                    </div>
                    <div class="user-footer-item">
                        <el-statistic title="活动" :value="666" />
                    </div>
                    <div class="user-footer-item">
                        <el-statistic title="好评" :value="888" />
                    </div>
                </div>
            </el-card>
            <el-card
                class="user-content"
                shadow="hover"
                :body-style="{ padding: '20px 50px', height: '100%', boxSizing: 'border-box' }"
            >
                <el-tabs tab-position="left" v-model="activeName">
                    <el-tab-pane name="label1" label="消息通知" class="user-tabpane">
                        <TabsComp />
                    </el-tab-pane>
                    <el-tab-pane name="label2" label="我的头像" class="user-tabpane">
                        <div class="crop-wrap" v-if="activeName === 'label2'">
                            <vueCropper
                                ref="cropper"
                                :img="imgSrc"
                                :autoCrop="true"
                                :centerBox="true"
                                :full="true"
                                mode="contain"
                                :outputQuality="1"
                            >
                            </vueCropper>
                        </div>
                        <el-button class="crop-demo-btn" type="primary"
                            >选择图片
                            <input class="crop-input" type="file" name="image" accept="image/*" @change="setImage" />
                        </el-button>
                        <el-button type="success" @click="saveAvatar">上传并保存</el-button>
                    </el-tab-pane>
                    <el-tab-pane name="label4" label="背景图片" class="user-tabpane">
                        <div class="crop-wrap" v-if="activeName === 'label4'">
                            <vueCropper
                                ref="cropper2"
                                :img="imgSrc2"
                                :autoCrop="true"
                                :centerBox="true"
                                :full="true"
                                mode="contain"
                                :outputQuality="1"
                            >
                            </vueCropper>
                        </div>
                        <el-button class="crop-demo-btn" type="primary"
                            >选择图片
                            <input class="crop-input" type="file" name="image" accept="image/*" @change="setImage2" />
                        </el-button>
                        <el-button type="success" @click="saveAvatar2">上传并保存</el-button>
                    </el-tab-pane>
                    <el-tab-pane v-if="role !='club'" name="label5" label="修改资料" class="user-tabpane">
                        <el-form class="w500" label-position="top">
                            <el-form-item label="昵称：">
                                <el-input :max="10" v-model="name"></el-input>
                            </el-form-item>
                            <el-form-item label="性别：">
                                <el-select v-model="sex" placeholder="请选择" style="width: 150px">
                                    <el-option
                                        v-for="item in sexSelect"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                             <el-form-item label="年龄">
                                <el-input-number :precision="0" :min="0" v-model="age" ></el-input-number>
                            </el-form-item>
                            <el-form-item label="个性签名：">
                                <el-input :max="30" v-model="description"></el-input>
                            </el-form-item>
                              <el-form-item>
                                <el-button type="primary" @click="saveUserData">保存</el-button>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                    <el-tab-pane name="label3" label="修改密码" class="user-tabpane">
                        <el-form class="w500" label-position="top">
                            <el-form-item label="旧密码：">
                                <el-input type="password" v-model="form.old"></el-input>
                            </el-form-item>
                            <el-form-item label="新密码：">
                                <el-input type="password" v-model="form.new"></el-input>
                            </el-form-item>
                            <el-form-item label="确认新密码：">
                                <el-input type="password" v-model="form.new1"></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="onSubmit">保存</el-button>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                
                </el-tabs>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts" name="ucenter">
import { reactive, ref } from 'vue';
import { VueCropper } from 'vue-cropper';
import 'vue-cropper/dist/index.css';
import TabsComp from '@/components/tabs.vue';
import { ElMessage } from 'element-plus';
import {ajax, uploadImgBase64 } from '@/api';
import {withLoading } from '@/utils/loading';
import {userData} from '@/store/userData';
const name = userData().name;
const role = userData().role;
const sex = ref(userData().sex || "女");
const age = ref<Number>(18);
const description = ref<string>("");

const form = reactive({
    new1: '',
    new: '',
    old: '',
});
const onSubmit = () => {};
const saveUserData = () => {
    let obj = {
        name: name,
        sex: sex.value,
        age: age.value,
        description: description.value,
    };
    updateUserApi(obj);
};

const activeName = ref('label1');
const avatar = userData().imgHead;
const avatarDecoration = userData().imgDecoration;
console.log("背景："+avatarDecoration);

const avatarImg = ref(avatar); //存储最终保存的图片，也是头像中的图片
const imgDecoration = ref(avatarDecoration); //存储最终保存的图片，也是背景中的图片
const fileName = ref('');
const imgSrc = ref(avatar); //剪切框中的原图
const imgSrc2 = ref(avatarDecoration); //剪切框中的原图
const cropImg = ref('');
const cropImg2 = ref('');
const cropper: any = ref();
const cropper2: any = ref();
const sexSelect = [
  {
    value: "男",
    label: '男',
  },
  {
    value: "女",
    label: '女',
  }
]
const setImage = (e: any) => {
    const file = e.target.files[0];
    if (!file.type.includes('image/')) {
        return;
    }
    fileName.value = file.name;
    const reader = new FileReader();
    reader.onload = (event: any) => {
        imgSrc.value = event.target.result;
        if( cropper.value ){
            cropper.value = event.target.result;
        }
    };
    reader.readAsDataURL(file);
};
const setImage2 = (e: any) => {
    const file = e.target.files[0];
    if (!file.type.includes('image/')) {
        return;
    }
    fileName.value = file.name;
    const reader = new FileReader();
    reader.onload = (event: any) => {
        imgSrc2.value = event.target.result;
        if( cropper2.value ){
            cropper2.value = event.target.result;
        }
    };
    reader.readAsDataURL(file);
};
const cropImage = () => {
    cropper.value.getCropData(data => {
        cropImg.value = data;
        avatarImg.value = cropImg.value;
         withLoading(uploadImgBase64Api("imgHead"),"上传中...");
    });
};
//上传背景图
const cropImage2 = () => {
    cropper2.value.getCropData(data => {
        cropImg2.value = data;
        imgDecoration.value = cropImg2.value;
         withLoading(uploadImgBase64Api("imgDecoration"),"上传中...");
    });
};
//点击保存及上传
const saveAvatar = () => {
    cropImage(); 
};
//点击保存背景图
const saveAvatar2 = () => {
    cropImage2(); 
};
/*************************  Api请求  *******************************/
//上传图片
const uploadImgBase64Api = async (type:string) => {
    let base;
    if( type == "imgHead" ){
        base = avatarImg.value;
    }else if( type == "imgDecoration" ){
        base = imgDecoration.value;
    }
    uploadImgBase64({
        url: "file/uploadImg",
        method: 'POST', // 修正参数名称
        base64: base,
        data:  {
            fileName: fileName.value // 传递文件名
        },
        success: (res) => {
            if( res.code == 0){
                if( type == "imgHead" ){
                    uploadImgHeadApi(res.data.url);
                }else if( type == "imgDecoration" ){
                    uploadImgDecorationApi(res.data.url);
                }
            }else{
                ElMessage.error(res.msg);
            }
        }
    });
};
//修改头像
const uploadImgHeadApi = async (url:any) => {
    ajax({
        url: "user/update/imgHead",
        method: 'POST', // 修正参数名称
        data:  {
            url: url // 传递文件名
        },
        success: (res) => {
            if( res.code == 0){
                userData().updateImgHead(res.data);
                ElMessage.success(res.msg);
            }else{
                ElMessage.error(res.msg);
            }
        }
    });
};
//修改背景图片
const uploadImgDecorationApi = async (url:any) => {
    ajax({
        url: "user/update/imgDecoration",
        method: 'POST', // 修正参数名称
        data:  {
            url: url // 传递文件名
        },
        success: (res) => {
            if( res.code == 0){
                userData().updateImgDecoration(res.data);
                ElMessage.success(res.msg);
            }else{
                ElMessage.error(res.msg);
            }
        }
    });
};
//修改用户信息
const updateUserApi = async (data:any) => {
    ajax({
        url: "wx/user/update",
        method: 'POST', // 修正参数名称
        data: data,
        success: (res) => {
            if( res.code == 0){
                ElMessage.success(res.msg);
            }else{
                ElMessage.error(res.msg);
            }
        }
    });
};
//查询用户信息
const findUserApi = async () => {
    ajax({
        url: "user/findMe",
        method: 'POST', // 修正参数名称
        success: (res) => {
            if( res.code == 0){
                sex.value = res.data.sex;
                age.value = res.data.age;
                description.value = res.data.description;
            }else{
                ElMessage.error(res.msg);
            }
        }
    });
};
if(role !='club'){
    findUserApi();
}

</script>

<style scoped>
.user-container {
    display: flex;
}

.user-profile {
    position: relative;
}

.user-profile-bg {
    width: 100%;
    height: 200px;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}

.user-profile {
    width: 500px;
    margin-right: 20px;
    flex: 0 0 auto;
    align-self: flex-start;
}

.user-avatar-wrap {
    position: absolute;
    top: 135px;
    width: 100%;
    text-align: center;
}

.user-avatar {
    border: 5px solid #fff;
    border-radius: 50%;
    overflow: hidden;
    box-shadow: 0 7px 12px 0 rgba(62, 57, 107, 0.16);
}

.user-info {
    text-align: center;
    padding: 80px 0 30px;
}

.info-name {
    margin: 0 0 20px;
    font-size: 22px;
    font-weight: 500;
    color: #373a3c;
}

.info-desc {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 5px;
}

.info-desc,
.info-desc a {
    font-size: 18px;
    color: #55595c;
}

.info-icon {
    margin-top: 10px;
}

.info-icon i {
    font-size: 30px;
    margin: 0 10px;
    color: #343434;
}

.user-content {
    flex: 1;
}

.user-tabpane {
    padding: 10px 20px;
}

.crop-wrap {
    width: 600px;
    height: 350px;
    margin-bottom: 20px;
}

.crop-demo-btn {
    position: relative;
}

.crop-input {
    position: absolute;
    width: 100px;
    height: 40px;
    left: 0;
    top: 0;
    opacity: 0;
    cursor: pointer;
}

.w500 {
    width: 500px;
}

.user-footer {
    display: flex;
    border-top: 1px solid rgba(83, 70, 134, 0.1);
}

.user-footer-item {
    padding: 20px 0;
    width: 33.3333333333%;
    text-align: center;
}

.user-footer > div + div {
    border-left: 1px solid rgba(83, 70, 134, 0.1);
}
</style>

<style>
.el-tabs.el-tabs--left {
    height: 100%;
}
</style>
